package com.cheneyjoo.util;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerInit {
    private ServerSocket ss;
    private boolean serverOnline = true;
    private Map<String, ServerThread> serverThreadMap = null;

    /**
     * 开启服务端
     *
     * @throws IOException
     */
    public void start() throws IOException {
        ss = new ServerSocket(8888);
        serverThreadMap=new HashMap<>();
        while (serverOnline) {
            System.out.println("等待客户端接入");
            Socket s = ss.accept();
            System.out.println("客户端连接成功" + s.getInetAddress() + ":" + s.getPort());
            ServerThread serverThread = new ServerThread(s);
            ExecutorService services = Executors.newCachedThreadPool();
            services.submit(serverThread);
            serverThreadMap.put(s.getInetAddress() + ":" + s.getPort(), serverThread);
        }
    }

    /**
     * 关闭服务端
     *
     * @throws IOException
     */
    public void stop() throws IOException {
        for (var thread: serverThreadMap.values()){
            thread.close();
        }
        ss.close();
        System.out.println("服务端已关闭");
    }
}
